package com.jiutong.meipengdai.ui.activitys;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.utils.StringUtil;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by suxi on 2017/6/1.
 */

public class TakePhotoActivity extends BaseActivity implements SurfaceHolder.Callback {
    @Bind(R.id.tv_album)
    TextView tvAlbum;
    @Bind(R.id.btn_takephoto)
    Button btnTakephoto;
    @Bind(R.id.tv_cancel)
    TextView tvCancel;
    @Bind(R.id.sv_photoview)
    SurfaceView surfaceView;
    @Bind(R.id.rl_take_photo)
    RelativeLayout rlTakePhoto;
    @Bind(R.id.tv_again)
    TextView tvAgain;
    @Bind(R.id.tv_usepic)
    TextView tvUsepic;
    @Bind(R.id.rl_makesure)
    RelativeLayout rlMakesure;

    private OrientationEventListener mOrEventListener;
    private boolean mCurrentOrientation;
    private Camera mCamera;
    public byte[] mData;

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_take_photo;
    }

    /* 图像数据处理还未完成时的回调函数 */
    private Camera.ShutterCallback mShutter = new Camera.ShutterCallback() {
        @Override
        public void onShutter() {
            // 一般显示进度条
        }
    };

    private String mFileName;
    /* 图像数据处理完成后的回调函数 */
    private Camera.PictureCallback mJpeg = new Camera.PictureCallback() {


        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            mData = data;
//            openActivity(ShowPicActivity.class);
            rlMakesure.setVisibility(View.VISIBLE);
            rlTakePhoto.setVisibility(View.GONE);
        }
    };

    /**
     * 将拍下来的照片存放在SD卡中
     * @param data
     * @throws IOException
     */
    public String saveToSDCard(byte[] data) throws IOException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
        String filename = format.format(date) + ".jpg";
        File fileFolder = new File(Environment.getExternalStorageDirectory()
                + "/jiutong/");
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"finger"的目录
            fileFolder.mkdir();
        }

        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); // 文件输出流
        outputStream.write(data); // 写入sd卡中
        outputStream.close(); // 关闭输出流
        return jpgFile.getAbsolutePath();
    }

    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
//        startOrientationChangeListener();
        SurfaceHolder holder = surfaceView.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.setKeepScreenOn(true);// 屏幕常亮
        holder.addCallback(this); // 回调接口
    }

    private final void startOrientationChangeListener() {
        mOrEventListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int rotation) {
                if (((rotation >= 0) && (rotation <= 45)) || (rotation >= 315)
                        || ((rotation >= 135) && (rotation <= 225))) {// portrait
                    mCurrentOrientation = true;
//                    Log.i(TAG, "竖屏");
                } else if (((rotation > 45) && (rotation < 135))
                        || ((rotation > 225) && (rotation < 315))) {// landscape
                    mCurrentOrientation = false;
//                    Log.i(TAG, "横屏");
                }
            }
        };
        mOrEventListener.enable();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        // SurfaceView尺寸发生改变时（首次在屏幕上显示同样会调用此方法），初始化mCamera参数，启动Camera预览
        Camera.Parameters parameters = mCamera.getParameters();// 获取mCamera的参数对象
        Camera.Size largestSize = getBestSupportedSize(parameters
                .getSupportedPreviewSizes());
        parameters.setPreviewSize(largestSize.width, largestSize.height);// 设置预览图片尺寸
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); //设置自动对焦
        largestSize = getBestSupportedSize(parameters
                .getSupportedPictureSizes());// 设置捕捉图片尺寸
        parameters.setPictureSize(largestSize.width, largestSize.height);
        mCamera.setParameters(parameters);

        try {
            mCamera.startPreview();
        } catch (Exception e) {
            if (mCamera != null) {
                mCamera.release();
                mCamera = null;
            }
        }

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // SurfaceView创建时，建立Camera和SurfaceView的联系
        if (mCamera != null) {
            try {
                mCamera.setDisplayOrientation(getPreviewDegree());
                mCamera.setPreviewDisplay(holder);
//                mCamera.startPreview(); // 开始预览
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 提供一个静态方法，用于根据手机方向获得相机预览画面旋转的角度
    public int getPreviewDegree() {
        // 获得手机的方向
        int rotation = this.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degree = 0;
        // 根据手机的方向计算相机预览画面应该选择的角度
        switch (rotation) {
            case Surface.ROTATION_0:
                degree = 90;
                break;
            case Surface.ROTATION_90:
                degree = 0;
                break;
            case Surface.ROTATION_180:
                degree = 270;
                break;
            case Surface.ROTATION_270:
                degree = 180;
                break;
        }
        return degree;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // SurfaceView销毁时，取消Camera预览
        if (mCamera != null) {
            mCamera.stopPreview();
        }
    }


    @SuppressLint("NewApi")
    @Override
    public void onResume() {
        super.onResume();
        // 开启相机
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            mCamera = Camera.open(0);
            // i=0 表示后置相机
        } else
            mCamera = Camera.open();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 释放相机
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }

    }

    private Camera.Size getBestSupportedSize(List<Camera.Size> sizes) {
        // 取能适用的最大的SIZE
        Camera.Size largestSize = sizes.get(0);
        int largestArea = sizes.get(0).height * sizes.get(0).width;
        for (Camera.Size s : sizes) {
            int area = s.width * s.height;
            if (area > largestArea) {
                largestArea = area;
                largestSize = s;
            }
        }
        return largestSize;
    }

    @OnClick({R.id.tv_album, R.id.btn_takephoto, R.id.tv_cancel,R.id.tv_again, R.id.tv_usepic})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_album://相冊
                selectImage();
                break;
            case R.id.btn_takephoto:
                mCamera.takePicture(mShutter, null, mJpeg);
                break;
            case R.id.tv_cancel://取消
                mData = null;
                finish();
                break;
            case R.id.tv_again://重拍
                mCamera.startPreview();
                rlTakePhoto.setVisibility(View.VISIBLE);
                rlMakesure.setVisibility(View.GONE);
                break;
            case R.id.tv_usepic://使用照片
                rlTakePhoto.setVisibility(View.GONE);
                rlMakesure.setVisibility(View.VISIBLE);

                try{
                    String filePath = saveToSDCard(mData);
                    Bundle bundle = new Bundle();
                    bundle.putString("picpath",filePath);
                    openActivity(EvaluateActivity.class, bundle);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {

                }

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mData = null;
    }

    private final int IMAGE_CODE = 0;
    private final String IMAGE_TYPE = "image/*";

    private void selectImage() {
        // TODO Auto-generated method stub
        boolean isKitKatO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        Intent getAlbum;
        if (isKitKatO) {
            getAlbum = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        }
        getAlbum.setType(IMAGE_TYPE);

        startActivityForResult(getAlbum, IMAGE_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode != RESULT_OK){
            Logger.e("select image error !!!");
            return;
        }

        if(requestCode == IMAGE_CODE){

            try {

                Uri uri = data.getData();
                String path = StringUtil.getPath(mContext, uri);
                Bundle bundle = new Bundle();
                bundle.putString("picpath",path);
                openActivity(EvaluateActivity.class, bundle);
                Logger.d(path);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }

        }
    }


}
